# zennotac-backend/app/routes/upload.py
from typing import List
from fastapi import APIRouter, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
import os
from app.utils.filename_helper import sanitize_filename
from app.config.base_setting import UPLOAD_FOLDER, backend_logger


router = APIRouter()

ALLOWED_EXTENSIONS = {'.pdf', '.jpg', '.jpeg', '.png', '.bmp'}

@router.post("/upload")
async def upload_files(files: List[UploadFile] = File(...)):
    uploaded_filenames = []
    skipped_files = []
    try:
        for file in files:
            decoded_filename = sanitize_filename(file.filename)
            safe_filename = os.path.basename(decoded_filename)
            ext = os.path.splitext(safe_filename)[1].lower()

            if ext not in ALLOWED_EXTENSIONS:
                backend_logger.warning(f"[UPLOAD] Skipped unsupported file: {safe_filename}")
                skipped_files.append(safe_filename)
                continue  # Skip this file and continue with the rest

            file_location = os.path.join(UPLOAD_FOLDER, safe_filename)

            contents = await file.read()
            with open(file_location, "wb") as f:
                f.write(contents)

            backend_logger.info(f"[UPLOAD] Saved: {safe_filename} ({len(contents)} bytes)")
            uploaded_filenames.append(safe_filename)

        if not uploaded_filenames:
            raise HTTPException(status_code=400, detail="No valid files uploaded.")

        return JSONResponse(content={
            "message": "Files ocred.",
            "uploaded_files": uploaded_filenames,
            "skipped_files": skipped_files
        })
    
    except Exception as e:
        backend_logger.exception(f"[UPLOAD ERROR] {str(e)}")
        raise HTTPException(status_code=500, detail="Upload failed, check backend logs for details")




# # zennotac-backend/app/routes/upload.py
# from fastapi import APIRouter, UploadFile, File, HTTPException
# from fastapi.responses import JSONResponse
# from app.utils.filename_helper import get_upload_file_path, sanitize_filename
# from app.config.base_setting import backend_logger
# import os

# router = APIRouter(tags=["Upload"])

# @router.post("/upload")
# async def upload_file(file: UploadFile = File(...)):
#     try:
#         # 1. Sanitize the filename
#         clean = sanitize_filename(file.filename)

#         # 2. Get absolute upload path (creates app/uploads/ if needed)
#         file_path = get_upload_file_path(clean)

#         # 3. Write file
#         data = await file.read()
#         with open(file_path, "wb") as f:
#             f.write(data)

#         # 4. Log and return sanitized name
#         filename = os.path.basename(file_path)
#         backend_logger.info(f"[UPLOAD] Saved: {filename} ({len(data)} bytes)")
#         return JSONResponse({"message": "File uploaded successfully", "filename": filename})

#     except Exception as e:
#         backend_logger.exception(f"[UPLOAD] {e}")
#         raise HTTPException(status_code=500, detail="Upload failed, check backend logs for details")
